//
//  PreferenceAreaViewController.m
//  PrintPort
//
//  Created by hy002 on 2018/1/25.
//  Copyright © 2018年 HUAYU. All rights reserved.
//

#import "PreferenceAreaViewController.h"
#import "PreferenModel.h"
#import "SecondTypeModel.h"
#import "CuXiaoModel.h"
#import "ProductTypeViewController.h"
#import "LiveSearchViewController.h"

#import "LivingGoodsViewController.h"
#import "LiveAllTypeViewController.h"
#import "SDCycleScrollView.h"
#import "BannerModel.h"
#import "ProdTypeModel.h"
#import "ProductModel.h"
#import "ImagelistModel.h"
#import "LiveGoodsDetailViewController.h"

static NSString *cellPath = @"PreferenceAreaCell";
@interface PreferenceAreaViewController ()<UITableViewDelegate,UITableViewDataSource,SDCycleScrollViewDelegate>
@property (nonatomic, strong)UITableView *tableview;
@property (nonatomic, strong)SDCycleScrollView *cycleScrollView;
@property (nonatomic, strong)UIView *navView;
@property (nonatomic, strong)PreferenModel *preModel;

@end

@implementation PreferenceAreaViewController
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.translucent = NO;
    _navView.hidden = NO;
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    _navView.hidden = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self creatUI];
    [self requestdiscount];
    
}

- (void)creatUI
{
    self.view.backgroundColor = BacksColor;
    self.navigationController.navigationBar.translucent = NO;
    self.navView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, STA_NAV_HEIGHT)];
    _navView.backgroundColor = [UIColor whiteColor];
    [self.navigationController.view addSubview:_navView];
    UIView *grayView = [[UIView alloc] initWithFrame:CGRectMake(20, STA_NAV_HEIGHT-35, SCREEN_WIDTH-40, 30)];
    grayView.backgroundColor = LinesColor;
    grayView.layer.cornerRadius = 15;
    grayView.layer.masksToBounds = YES;
    [_navView addSubview:grayView];
    UIImageView *imgView = [ZCControl createImageViewWithFrame:CGRectMake(10, 5, 20, 20) ImageName:@"shouyess"];
    imgView.contentMode = UIViewContentModeScaleAspectFit;
    [grayView addSubview:imgView];
    UILabel *pladerLab = [ZCControl createLabelWithFrame:CGRectMake(40, 0, SCREEN_WIDTH-120, 30) Font:12.0 Text:@"输入您要搜索的内容" Color:BlaTiColor];
    pladerLab.textAlignment = NSTextAlignmentCenter;
    [grayView addSubview:pladerLab];
    UIButton *searchBtn = [ZCControl createButtonWithFrame:CGRectMake(0, 0, SCREEN_WIDTH-40, 30) ImageName:nil Target:self Action:@selector(searchBtnAction) Title:nil Font:14.0];
    searchBtn.backgroundColor = [UIColor clearColor];
    [grayView addSubview:searchBtn];
    
    self.tableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-STA_NAV_HEIGHT-SCREER_HeiX-TABBAR_HEIGHT) style:UITableViewStylePlain];
    _tableview.delegate = self;
    _tableview.dataSource = self;
    _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableview.backgroundColor = BacksColor;
    [self.view addSubview:_tableview];
    self.tableview.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewHeaderData)];
    self.tableview.estimatedRowHeight = 0;
    self.tableview.estimatedSectionHeaderHeight = 0;
    self.tableview.estimatedSectionFooterHeight = 0;
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 190*displaywidth)];
    self.cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 190*displaywidth) delegate:self placeholderImage:nil];
    _cycleScrollView.pageControlAliment = SDCycleScrollViewPageContolAlimentRight;
    _cycleScrollView.delegate = self;
    //是否自动轮播
    _cycleScrollView.autoScroll = YES;//是否自动轮播 bannerImageViewContentMode
    //图片样式
    _cycleScrollView.bannerImageViewContentMode = UIViewContentModeScaleAspectFill;
    _cycleScrollView.clipsToBounds = YES;
    _cycleScrollView.currentPageDotColor = ThemeColor;
    _cycleScrollView.pageDotColor = [UIColor whiteColor];
    _cycleScrollView.pageControlStyle = SDCycleScrollViewPageContolStyleClassic;
    [headerView addSubview:_cycleScrollView];
    self.tableview.tableHeaderView = headerView;
    
    
}



- (void)loadNewHeaderData
{
    [self requestdiscount];
}

//搜索
- (void)searchBtnAction
{
    LiveSearchViewController *vc = [[LiveSearchViewController alloc] init];
    vc.areaId = @"4";
    [self.navigationController pushViewController:vc animated:YES];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0)
    {
        return 1;
    }
    if (section == 1)
    {
        return 2;
    }
    else
    {
        if (_preModel)
        {
            NSArray *array = _preModel.productList;
            return array.count;
        }
        return 0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (!cell)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellPath];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (_preModel)
    {
        if (indexPath.section == 0)
        {
            NSArray *typeAry = _preModel.productTypeList;
            NSInteger num = typeAry.count;
            if (typeAry.count > 10)
            {
                num = 10;
            }
            CGFloat W = SCREEN_WIDTH/5;
            for (int i = 0; i < num; i++)
            {
                SecondTypeModel *typeModel = typeAry[i];
                UIImageView *imageview = [ZCControl createImageViewWithFrame:CGRectMake((W-40*displaywidth)/2+W*(i%5), 10*displaywidth+(i/5)*80*displaywidth, 40*displaywidth, 40*displaywidth) ImageName:@""];
                NSString *nameStr = typeModel.typeName;
                if (typeAry.count > 10 && i == 9)
                {
                    imageview.image = [UIImage imageNamed:@"quanb"];
                    nameStr = @"全部";
                }
                else
                {
                    [imageview sd_setImageWithURL:[NSURL URLWithString:typeModel.imgUrl]];
                }
                imageview.contentMode = UIViewContentModeScaleAspectFit;
                imageview.layer.cornerRadius = 20*displaywidth;
                imageview.layer.masksToBounds = YES;
                [cell.contentView addSubview:imageview];
                UILabel *nameLab = [ZCControl createLabelWithFrame:CGRectMake(W*(i%5), 50*displayheight+(i/5)*80*displaywidth, W, 30*displaywidth) Font:12.0 Text:nameStr Color:RGB(77, 77, 77)];
                nameLab.textAlignment = NSTextAlignmentCenter;
                [cell.contentView addSubview:nameLab];
                UIButton *btn = [ZCControl createButtonWithFrame:CGRectMake(W*(i%5), 80*displaywidth*(i/5), W, 79*displayheight) ImageName:nil Target:self Action:@selector(closeProdTypeAction:) Title:nil Font:12.0];
                btn.backgroundColor = [UIColor clearColor];
                btn.tag = 100+i;
                [cell.contentView addSubview:btn];
                
            }
            CGFloat H = 79*displaywidth;
            if (num > 5)
            {
                H = 159*displaywidth;
            }
            UIView *lineAview = [[UIView alloc] initWithFrame:CGRectMake(0, H, SCREEN_WIDTH, 1*displaywidth)];
            lineAview.backgroundColor = LinesColor;
            [cell.contentView addSubview:lineAview];

        }
        else if (indexPath.section == 1)
        {
            NSArray *titAry = @[@"- 优惠促销 -",@"- 热销商品 -"];
            UILabel *titLabel = [ZCControl createLabelWithFrame:CGRectMake(15*displaywidth, 0, SCREEN_WIDTH-30*displaywidth, 40*displaywidth) Font:16.0 Text:titAry[indexPath.row] Color:BlaTiColor];
            titLabel.textAlignment = NSTextAlignmentCenter;
            [cell.contentView addSubview:titLabel];
            UIView *aview = [[UIView alloc] initWithFrame:CGRectMake(0, 39*displaywidth, SCREEN_WIDTH, 1*displaywidth)];
            aview.backgroundColor = LinesColor;
            [cell.contentView addSubview:aview];
            if (indexPath.row == 0)
            {
                NSArray *imageAry = _preModel.preferentialDiscountList;
                if (imageAry.count > 0)
                {
                    CGRect arect = CGRectMake(12.5*displaywidth, 50*displaywidth, SCREEN_WIDTH/2-15*displaywidth, 230*displaywidth);
                    CGRect brect = CGRectMake(SCREEN_WIDTH/2+2.5*displaywidth, 50*displaywidth, SCREEN_WIDTH/2-15*displaywidth, 112.5*displaywidth);
                    CGRect crect = CGRectMake(SCREEN_WIDTH/2+2.5*displaywidth, 165*displaywidth, SCREEN_WIDTH/2-15*displaywidth, 112.5*displaywidth);
                    NSValue *avalue = [NSValue valueWithCGRect:arect];
                    NSValue *bvalue = [NSValue valueWithCGRect:brect];
                    NSValue *cvalue = [NSValue valueWithCGRect:crect];
                    NSArray *rectAry = @[avalue,bvalue,cvalue];
                    for (int i = 0; i < imageAry.count; i++)
                    {
                        CuXiaoModel *model = imageAry[i];
                        if (i < 3)
                        {
                            UIImageView *imgView = [ZCControl createImageViewWithFrame:[rectAry[i] CGRectValue] ImageName:@""];
                            if (![model.imgUrl isEqualToString:@""])
                            {
                                [imgView sd_setImageWithURL:URL(model.imgUrl)];
                            }
                            imgView.contentMode = UIViewContentModeScaleAspectFill;
                            imgView.layer.masksToBounds = YES;
                            [cell.contentView addSubview:imgView];
                            UIButton *btn = [ZCControl createButtonWithFrame:[rectAry[i] CGRectValue] ImageName:nil Target:self Action:@selector(closeDiscount:) Title:nil Font:12.0];
                            btn.backgroundColor = [UIColor clearColor];
                            objc_setAssociatedObject(btn, "firstObject", model.sourceId, OBJC_ASSOCIATION_RETAIN_NONATOMIC);   //实际上就是KVC
                            [cell.contentView addSubview:btn];
                        }
                    }
                }
                UIView *bview = [[UIView alloc] initWithFrame:CGRectMake(0, 289*displaywidth, SCREEN_WIDTH, 1*displaywidth)];
                bview.backgroundColor = LinesColor;
                [cell.contentView addSubview:bview];
                
            }
            else
            {
                NSArray *hotAry = _preModel.preferentialHotSaleList;
                if (hotAry.count > 0)
                {
                    CGFloat w = (SCREEN_WIDTH-2*displaywidth)/3;
                    for (int i = 0; i < hotAry.count; i++)
                    {
                        CuXiaoModel *model = hotAry[i];
                        UIImageView *imgView = [ZCControl createImageViewWithFrame:CGRectMake((w+0.5*displaywidth)*i, 40*displaywidth, w, 150*displaywidth) ImageName:@""];
                        if (![model.imgUrl isEqualToString:@""])
                        {
                            [imgView sd_setImageWithURL:URL(model.imgUrl)];
                        }
                        imgView.contentMode = UIViewContentModeScaleAspectFill;
                        imgView.layer.masksToBounds = YES;
                        [cell.contentView addSubview:imgView];
                        UIButton *hotbutton = [ZCControl createButtonWithFrame:CGRectMake((w+0.5*displaywidth)*i, 40*displaywidth, w, 150*displaywidth) ImageName:nil Target:self Action:@selector(closeHotShoping:) Title:nil Font:12.0];
                        hotbutton.backgroundColor = [UIColor clearColor];
                        objc_setAssociatedObject(hotbutton, "firstObject", model.sourceId, OBJC_ASSOCIATION_RETAIN_NONATOMIC);   //实际上就是KVC
                        [cell.contentView addSubview:hotbutton];
                    }
                }
                if (_preModel.preferentialHorizontal)
                {
                    BannerModel *banmodel = _preModel.preferentialHorizontal;
                    UIImageView *imgView = [ZCControl createImageViewWithFrame:CGRectMake(0, 190*displaywidth, SCREEN_WIDTH, 120*displaywidth) ImageName:@""];
                    if (![banmodel.imgUrl isEqualToString:@""])
                    {
                        [imgView sd_setImageWithURL:URL(banmodel.imgUrl)];
                    }
                    imgView.contentMode = UIViewContentModeScaleAspectFill;
                    imgView.layer.masksToBounds = YES;
                    [cell.contentView addSubview:imgView];
                }
                UILabel *nameLab = [ZCControl createLabelWithFrame:CGRectMake(15*displaywidth, 310*displaywidth, 160*displaywidth, 29*displaywidth) Font:13.0 Text:@"推荐商品" Color:RGB(77, 77, 77)];
                [cell.contentView addSubview:nameLab];
                UIView *cview = [[UIView alloc] initWithFrame:CGRectMake(0, 339*displaywidth, SCREEN_WIDTH, 1*displaywidth)];
                cview.backgroundColor = LinesColor;
                [cell.contentView addSubview:cview];
            }
        }
        else
        {
            NSArray *shopAry = _preModel.productList;
            if (shopAry.count > 0)
            {
                ProductModel *productModel = shopAry[indexPath.row];
                NSArray *imgArray = productModel.productImgList;
                UIImageView *imgView = [ZCControl createImageViewWithFrame:CGRectMake(15*displaywidth, 10*displaywidth, 80*displaywidth, 80*displaywidth) ImageName:@""];
                if (imgArray.count > 0)
                {
                    ImagelistModel *imgModel = imgArray[0];
                    [imgView sd_setImageWithURL:[NSURL URLWithString:imgModel.imgUrl]];
                }
                imgView.contentMode = UIViewContentModeScaleAspectFill;
                imgView.layer.masksToBounds = YES;
                [cell.contentView addSubview:imgView];
                UILabel *titlab = [ZCControl createLabelWithFrame:CGRectMake(115*displaywidth, 5*displaywidth, SCREEN_WIDTH-130*displaywidth, 35*displaywidth) Font:12.0 Text:productModel.productName Color:RGB(77, 77, 77)];
                titlab.lineBreakMode = NSLineBreakByTruncatingTail;
                titlab.adjustsFontSizeToFitWidth = NO;
                [cell.contentView addSubview:titlab];
                
                UILabel *moneyLab = [ZCControl createLabelWithFrame:CGRectMake(115*displaywidth, 70*displaywidth, 100*displaywidth, 20*displaywidth) Font:12.0 Text:[NSString stringWithFormat:@"%@",productModel.priceDescribe] Color:RGB(241, 90, 36)];
                CGRect abounds = [moneyLab.text boundingRectWithSize:CGSizeMake(SCREEN_WIDTH-200*displaywidth, 20*displaywidth) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:NormalFontWithSize(12.0+fontScale)} context:nil];
                CGFloat width1 = abounds.size.width+10;
                moneyLab.frame = CGRectMake(115*displaywidth, 70*displaywidth, width1, 20*displaywidth);
                [cell.contentView addSubview:moneyLab];
                
                UILabel *numLab = [ZCControl createLabelWithFrame:CGRectMake(width1+140*displaywidth, 70*displaywidth, 100*displaywidth, 20*displaywidth) Font:12.0 Text:[NSString stringWithFormat:@" %@购买",productModel.productSales] Color:RGB(179, 179, 179)];
                [cell.contentView addSubview:numLab];
                
                UIView *lineFView = [[UIView alloc] initWithFrame:CGRectMake(0, 99*displaywidth, SCREEN_WIDTH, 1*displaywidth)];
                lineFView.backgroundColor = LinesColor;
                [cell.contentView addSubview:lineFView];
            }
            
        }
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 2)
    {
        NSArray *shopAry = _preModel.productList;
        ProductModel *productModel = shopAry[indexPath.row];
        LiveGoodsDetailViewController *vc = [[LiveGoodsDetailViewController alloc] init];
        vc.idStr = s_str(productModel.ID);
        vc.isTeHui = YES;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0)
    {
        if (_preModel)
        {
            NSArray *typeAry = _preModel.productTypeList;
            if (typeAry.count > 5)
            {
                return 160*displaywidth;
            }
            return 80*displaywidth;
        }
        return 160*displaywidth;
    }
    else if (indexPath.section == 1)
    {
        if (indexPath.row == 0)
        {
            return 290*displaywidth;
        }
        return 340*displaywidth;
    }
    else
    {
        return 100*displaywidth;
    }
}

//优惠促销
- (void)closeDiscount:(UIButton *)btn
{
    NSString *idstr = objc_getAssociatedObject(btn, "firstObject");
    LiveGoodsDetailViewController *vc = [[LiveGoodsDetailViewController alloc] init];
    vc.idStr = s_str(idstr);
    vc.isTeHui = YES;
    [self.navigationController pushViewController:vc animated:YES];

}

//热销商品
- (void)closeHotShoping:(UIButton *)btn
{
    NSString *idstr = objc_getAssociatedObject(btn, "firstObject");
    LiveGoodsDetailViewController *vc = [[LiveGoodsDetailViewController alloc] init];
    vc.idStr = s_str(idstr);
    vc.isTeHui = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)closeProdTypeAction:(UIButton *)btn
{
    NSArray *typeAry = _preModel.productTypeList;
    SecondTypeModel *model = typeAry[btn.tag-100];
    ProductTypeViewController *vc = [[ProductTypeViewController alloc] init];
    vc.areaid = @"4";
    if (typeAry.count > 10 && btn.tag == 109)
    {
        vc.isAll = YES;
        vc.titStr = @"分类列表";
    }
    else
    {
        vc.parentId = model.ID;
        vc.titStr = model.typeName;
        vc.isAll = NO;
    }
    [self.navigationController pushViewController:vc animated:YES];

}

- (void)requestdiscount
{
    WEAKSELF;
    [HYBaseHandler requestWithTheFormUrl:SERVER_HomeDiscount Parmers:nil Success:^(id obj) {
        [weakSelf.tableview.mj_header endRefreshing];
        if ([obj server_Getcodecheck])
        {
            weakSelf.preModel = [PreferenModel mj_objectWithKeyValues:obj[@"data"]];
            dispatch_async(dispatch_get_main_queue(), ^{
                NSArray *bannerAry = weakSelf.preModel.bannerList;
                NSMutableArray *imgAry = [NSMutableArray arrayWithCapacity:0];
                for (BannerModel *model in bannerAry)
                {
                    [imgAry addObject:model.imgUrl];
                }
                weakSelf.cycleScrollView.imageURLStringsGroup = imgAry;
                [weakSelf.tableview reloadData];
            });
        }
        else
        {
            [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
        }
    } failed:^(NSError *error) {
        [weakSelf.tableview.mj_header endRefreshing];

    }];
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
